/**图片压缩变更方法 */
export const imageMin = async (params: {
  file?: File
  url?: string
  quality?: number
  maxLength?: number,
  size?: {height: number, width: number},
  fileName?: string
} = {quality: 1, fileName: '图片'}) => {
  console.assert(params.file || params.url, '必须存在file或者url入参')
  const img = await toImage({file: params.file, url: params.url})
  const canvas = toCanvas(img, {size: params.size, maxLength: params.maxLength})
  const file = await canvasToFile(canvas, {quality: params.quality as number, fileName: params.fileName as string})
  return file
}

/**处理图片压缩，并且转成url */
export const imageMinByUrl = async (
  params: {
    file?: File
    url?: string
    quality?: number
    maxLength?: number,
    size?: {height: number, width: number},
  } = {quality: 1}
) => {
  console.assert(params.file || params.url, '必须存在file或者url入参')
  const img = await toImage({file: params.file, url: params.url})
  const canvas = toCanvas(img, {size: params.size, maxLength: params.maxLength})
  return canvas.toDataURL('image/png', params.quality)
}

/**转换成图片 */
async function toImage (params: {file?: File, url?: string}): Promise<HTMLImageElement> {
  return new Promise((reso, rej) => {

    const {file, url} = params
    const img = new Image()
    img.onload = () => {
      return reso(img)
    }
    // 文件方式
    if (file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        img.setAttribute('src', e.target?.result as string)
      }
      reader.readAsDataURL(file)
    } else if (url) {
      img.setAttribute('src', url)
    } else {
      console.error(`解析图片出错`)
    }
  })
}

/**转换成canvas */
function toCanvas (img: HTMLImageElement, options?: {size?: {width: number, height: number}, maxLength?: number}) {
  const canvas = document.createElement('canvas')
  let {size, maxLength} = options ?? {}
  let {height, width} = img
  if (size || maxLength) {
    if ((!size?.height || !size.width) && !maxLength) maxLength = size?.height ?? size?.width
    // 设置长度并去适应
    if (maxLength) {
      let maxlen = Math.max(height, width)
      let rate = maxLength / maxlen
      height = maxlen === height ? maxLength : height * rate
      width = maxlen === width ? maxLength : width * rate
    } else if (size) {
      // 设置了尺寸
      height = size.height
      width = size.width
    }
  }
  canvas.height = height
  canvas.width = width
  const ctv = canvas.getContext('2d')
  ctv?.drawImage(img, 0, 0, width, height)
  return canvas
}

/**canvas转文件 */
function canvasToFile (canvas: HTMLCanvasElement, options: {fileName?: string, quality?: number} = {quality: 1, fileName: '图片'}): Promise<File> {
  return new Promise((reso, rej) => {
    canvas.toBlob((blob) => {
      const file = new File([ blob as Blob ], options!.fileName as string, {
        type: 'image/png',
      })
      reso(file)
    }, '', options.quality)
  })
}
